package com.authine.cloudpivot.ext.service.impl;

import com.authine.cloudpivot.ext.Utils.DocAPI;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.ext.service.RoleAuthService;
import com.authine.cloudpivot.web.api.exception.PortalException;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Author hxd
 * @Date 2022/9/21 9:44
 * @Description
 **/
@Service
@Slf4j
public class RoleAuthServiceImpl implements RoleAuthService {

    @Autowired
    CloudSqlService cloudSqlService;


    public  void  RoleAuthDis(String PosDuty,String PosName,String AuthFileId)  {
        String PosFid="";
        String RolePosName="";
        String RolePosId="";
        String AssRolePosId="";
        String sql = "select fid,  fname_l2 ,FNUMBER from  T_ORG_Position where  fnumber='"+ PosDuty + "'";
        Map<String, Object> result = cloudSqlService.getMap(CloudSqlService.htEas,sql);

        try {

            while (!result.isEmpty() && !PosName.equalsIgnoreCase("董事长")){
                PosFid = MapUtils.getString(result,"fid");
                PosName = MapUtils.getString(result,"fname_l2");
                PosDuty= MapUtils.getString(result,"FNUMBER");
                RolePosName = PosDuty + " "+ PosName;
                JSONObject RoleMainPosObj = DocAPI.getRole(RolePosName);
                int RoleMainPosNum=Integer.parseInt(RoleMainPosObj.getString("num"));
                if(RoleMainPosNum==0){
                    continue;
                }
                JSONArray RoleMainPosDataArray = RoleMainPosObj.getJSONArray("data");
                JSONObject RoleMainPosDataObj = RoleMainPosDataArray.getJSONObject(RoleMainPosDataArray.size()-1);
                RolePosId = RoleMainPosDataObj.getString("id");
                DocAPI.getRoleAuth(RolePosName, RolePosId,"VPD", AuthFileId);
                sql = "select B.fname_l2 as fname_l2,B.FNUMBER as FNUMBER ,B.FID from  T_ORG_PositionHierarchy A inner join T_ORG_POSITION B ON A.FPARENTID=B.FID where  A.fchildid='"+ PosFid + "'";
                result = cloudSqlService.getMap(CloudSqlService.htEas,sql);
            }
        }catch (Exception e) {
            e.printStackTrace();
            throw  new PortalException(-1l,"文件 授权失败");
        }


    }
}
